<template>
  <div class="addtalk">
    <div class="header-with-back">
      <div class="back-nav" @click="goToIndex">
        <van-icon name="arrow-left" />
        <span style="font-size: 1.2rem">上传资源</span>
      </div>
      <div class="top_right" @click="submit">
        <van-button class="submit_button" type="info">发布</van-button>
      </div>
    </div>

    <van-notice-bar scrollable left-icon="volume">
      温馨提示：发布请注意文明用语！良言一句三冬暖，恶语伤人六月寒！
    </van-notice-bar>

    <div class="achievement-container">
      <div class="addresource_nr_big">
        <van-cell-group>
          <van-field
              type="textarea"
              v-model="resourceName"
              label="资源名称"
              placeholder="请输入资源名称"
              rows="2"
              autosize
              required
          />
        </van-cell-group>
        <van-cell-group>
          <van-field
              type="textarea"
              v-model="resourceDescription"
              label="描述"
              placeholder="请输入资源描述"
              rows="4"
              autosize
              maxlength="50"
              show-word-limit
          />
        </van-cell-group>

        <van-dropdown-menu>
          <van-dropdown-item
              v-model="resourceType"
              :options="option"
              duration=0.5
          />
        </van-dropdown-menu>

        <div class="upload-section">
          <div class="upload-title">上传资源</div>
          <van-uploader
              v-model="fileList"
              :max-count="1"
              :before-read="beforeRead"
              accept="*/*"
          >
            <van-button
                icon="plus"
                type="primary"
                color="rgb(83, 30, 88)"
            >选择文件</van-button>
          </van-uploader>

          <!-- 已上传文件展示区域 -->
          <div class="uploaded-files" v-if="fileList.length > 0">
            <div class="file-item" v-for="(file, index) in fileList" :key="index">
              <van-icon name="description" class="file-icon" />
              <div class="file-info">
                <div class="file-name">{{ file.file.name }}</div>
                <div class="file-size">{{ formatFileSize(file.file.size) }}</div>
                <div class="file-status" v-if="file.status">{{ getStatusText(file.status) }}</div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts" name="ResourceShareUploaderView">
import { ref } from "vue";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo'
import { useRouter } from 'vue-router';
import {addResourceUsingPost} from "../../Api/jiaoshimokuai";
import { showToast} from "vant";
import {uploadUsingPost} from "../../Api/wenjianshangchuanmokuai";

const router = useRouter();
const userStore = useUserStore();

// 返回资源
function goToIndex() {
  router.push('/resourceshare');
}

// 总体表单
const resourceDescription = ref('');
const resourceName = ref('');
const resourceType = ref(0);
const uploaderId = ref(userStore.userInfo.username);
const fileList = ref([]); // 存储上传的文件列表

// 文件类型验证（修改为只验证大小）
const beforeRead = (file) => {
  // 文件大小限制 (50MB)
  const maxSize = 50 * 1024 * 1024;
  if (file.size > maxSize) {
    showToast('文件大小不能超过50MB');
    return false;
  }

  return true;
};

// 文件上传处理
const submit = async () => {
  // 验证表单
  if (!resourceName.value) {
    showToast('请输入资源名称');
    return;
  }

  if (fileList.value.length === 0) {
    showToast('请选择文件');
    return;
  }

  try {
    showToast('文件上传中...');
    const file = fileList.value[0];
    file.status = 'uploading';

    // 创建FormData
    const formData = new FormData();
    formData.append('file', file.file);

    // 上传文件
    const uploadRes = await uploadUsingPost({
      file: file.file
    });

    if (uploadRes.data.code !== 0) {
      file.status = 'failed';
      showToast('文件上传失败: ' + (uploadRes.data.message || ''));
      return;
    }

    file.status = 'done';
    const fileUrl = uploadRes.data.data;

    // 提交表单数据
    showToast('正在提交资源信息...');
    const submitRes = await addResourceUsingPost({
      resourceDescription: resourceDescription.value,
      resourceName: resourceName.value,
      resourceType: resourceType.value,
      storagePath: fileUrl,
      uploaderId: userStore.userInfo.userId
    });

    if (submitRes.data.code === 0) {
      showToast('发布成功');
      router.push('/resourceshare');
    } else {
      showToast('提交失败: ' + (submitRes.data.message || ''));
    }
  } catch (error) {
    if (fileList.value[0]) {
      fileList.value[0].status = 'failed';
    }
    showToast('操作失败，请重试');
    console.error('上传错误详情：', error);
  }
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    uploading: '上传中...',
    done: '上传成功',
    failed: '上传失败'
  };
  return statusMap[status] || '';
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 类型定义
const option = [
  { text: '教案', value: 0 },
  { text: '课件', value: 1 },
  { text: '教学视频', value: 2 },
  { text: '其它', value: 3 },
];

</script>

<style scoped>
.addtalk {
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.achievement-container {
  height: 100vh;
  overflow-y: auto;
  padding: 10px;
  margin-top: 4%;
}
.header-with-back {
  height: 40px;
  background-color: #f8f8f8;
  padding: 10px;
  text-align: left;
  font-size: 20px;
  color: #682757;
  line-height: 40px;
  overflow: hidden;
  min-width: 100%;
  position: fixed;
  z-index: 999;
}
/*返回*/
.back-nav {
  position: fixed;
  left: 1%;
  top: 0.5%;
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  color: rgb(83, 30, 88);
  padding: 0.5rem;
  z-index: 10;
  font-size: 0.9rem;
}

/*返回符号*/
.header-with-back .van-icon {
  position: static;
  font-size: 1.35rem;
}

.top_right{
  line-height: 30px;
  display: inline-block;
  float: right;
  margin-right: 20px;
}
.submit_button{
  background-color: #682757;
  color: #f9f9f9;
  border-radius: 60px;
  width: 70px;
  height: 35px;
  border: none;
}

/* 下拉框基础样式 */
:deep(.van-dropdown-menu) {
  display: flex;
  max-height: 20%;
  margin-left: 3%;
  width: auto !important;
}

/* 下拉框初始样式 */
:deep(.van-dropdown-item) {
  max-width: 88%;
  max-height: 26%;
  margin-left: 6%;
  width: auto !important;
}

/*下拉框伸展展示底部样式*/
:deep(.van-overlay) {
  width: 50% !important;
  height: 50% !important;
}

/*菜单未展开样式*/
:deep(.van-dropdown-menu__bar, .van-dropdown-menu__bar--opened) {
  background-color: rgb(253, 253, 254) !important;
  box-shadow: none !important;
}

/* 下拉框伸展样式 */
:deep(.van-dropdown-item--down) {
  background-color: white !important;
}

.upload-section {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
}

.upload-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

/* 已上传文件样式 */
.uploaded-files {
  margin-top: 16px;
  border-top: 1px solid #f5f5f5;
  padding-top: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-bottom: 8px;
}

.file-icon {
  font-size: 24px;
  color: #409eff;
  margin-right: 12px;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #999;
}

.delete-icon {
  font-size: 16px;
  color: #f56c6c;
  margin-left: 8px;
  cursor: pointer;
}

</style>
